package com.limh.gobang.activity

import android.app.Activity
import android.content.Context
import android.content.DialogInterface
import android.content.Intent
import android.content.pm.PackageManager
import android.util.Log
import android.view.KeyEvent
import android.view.MenuItem
import android.widget.TextView
import android.widget.Toast
import com.limh.gobang.R
import com.limh.gobang.base.BaseActivity
import com.limh.gobang.base.Consts
import com.limh.gobang.base.Consts.bgColor
import com.limh.gobang.bean.Fight
import com.limh.gobang.bean.User
import com.limh.gobang.service.WebConfiguration
import com.limh.gobang.service.utils.StreamToolkit
import com.limh.gobang.utils.GsonUtils
import com.limh.gobang.utils.QRUtils
import com.limh.gobang.utils.SpUtils
import com.limh.gobang.view.CommDialog
import com.limh.gobang.view.callback.ResultCallback
import io.github.xudaojie.qrcodelib.CaptureActivity
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.android.synthetic.main.layout_main.*


class MainActivity : BaseActivity() {

    private var webConfig: WebConfiguration? = null
    private val CODE_REQUEST = 11
    private lateinit var user: User
    private lateinit var txtUserHead: TextView
    private lateinit var txtNick: TextView
    private var dialog: CommDialog? = null

    override fun findView() {
        setContentView(R.layout.activity_main)
    }

    override fun initViews() {
        navigation.setNavigationItemSelectedListener({ item: MenuItem ->
            when (item.itemId) {
                R.id.item_1 -> {
                }
                R.id.item_2 -> {
                    share()
                }
                R.id.item_3 -> {
                    showMsgDialog("当前版本", getString(R.string.app_name) + "V" + getLocalVersionName(this))
                }
                R.id.item_4 -> {
                    startActivity(Intent(this, LoginActivity::class.java))
                    finish()
                }
            }
            if (drawerNv.isDrawerVisible(navigation)) {
                drawerNv.closeDrawer(navigation)
            }
            return@setNavigationItemSelectedListener true
        })

        navigation.itemIconTintList = null

        imageMenu.setOnClickListener {
            if (drawerNv.isDrawerOpen(navigation)) {
                drawerNv.closeDrawer(navigation)
            } else {
                drawerNv.openDrawer(navigation)
            }
        }

        val headView = navigation.getHeaderView(0)
        txtNick = headView.findViewById(R.id.txtNick)
        txtUserHead = headView.findViewById(R.id.txtUserHead)
    }

    override fun initDatas() {

        webConfig = WebConfiguration()
        webConfig!!.address = StreamToolkit.getLocalIp(this)
        webConfig!!.port = StreamToolkit.getPort()

        btnCreateRoom.setOnClickListener {
            val intent = Intent(this, PlayActivity::class.java)
            intent.putExtra("webConfig", webConfig)
            intent.putExtra("type", "server")
            val fight = Fight()
            fight.isFirst = true
            fight.color = ResultCallback.WHITE
            fight.point = null
            intent.putExtra("fight", fight)
            startActivity(intent)
        }

        btnJoinRoom.setOnClickListener {
            startActivityForResult(Intent(this, CaptureActivity::class.java), CODE_REQUEST)
        }

        user = GsonUtils.str2Bean(SpUtils.get(this, Consts.SP_USER, "") as String, User::class.java)
        Log.d(TAG, "$user")
        txtUserHead.text = if (user.username!!.length > 2) {
            user.username!!.substring(user.username!!.length - 2)
        } else {
            user.username
        }
        txtUserHead.setBackgroundResource(bgColor[user.userbgId!!])
        txtNick.text = user.username
    }

    /**
     * 展示分享二维码
     */
    fun share() {
        val str = "http://fir.im/gv92"
        val builder = CommDialog.Builder(this)
        builder.showImage(QRUtils.createBitmap(str, 200, 200)!!)
        builder.setTitle(getString(R.string.app_name))
        builder.setCancel("取消", DialogInterface.OnClickListener { dialog, _ ->
            dialog.dismiss()
        })
        builder.setConfirm("分享到", DialogInterface.OnClickListener { dialog, _ ->
            val intent = Intent(Intent.ACTION_SEND)
            intent.type = "text/plain"
            intent.putExtra(Intent.EXTRA_SUBJECT, getString(R.string.app_name))
            intent.putExtra(Intent.EXTRA_TEXT, getString(R.string.app_name)+"\n"+str)
            intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
            startActivity(Intent.createChooser(intent, "分享到"))
            dialog.dismiss()
        })
        dialog = builder.create()
        dialog!!.show()
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == CODE_REQUEST) {
            if (resultCode == Activity.RESULT_OK) {
                val result = data!!.getStringExtra("result")
                Log.e(TAG, "扫描结果=$result")
                val clientIntent = Intent(this, PlayActivity::class.java)
                clientIntent.putExtra("webConfig", GsonUtils.str2Bean(result, WebConfiguration::class.java))
                clientIntent.putExtra("type", "client")
                val fight = Fight()
                fight.isFirst = false
                fight.color = ResultCallback.BLACK
                fight.point = null
                clientIntent.putExtra("fight", fight)
                startActivity(clientIntent)
            }
        }
    }

    /**
     * 获取版本名称
     */
    fun getLocalVersionName(ctx: Context): String {
        var localVersion = ""
        try {
            val packageInfo = ctx.applicationContext
                    .packageManager
                    .getPackageInfo(ctx.packageName, 0)
            localVersion = packageInfo.versionName
            Log.d("TAG", "本软件的版本号。。$localVersion")
        } catch (e: PackageManager.NameNotFoundException) {
            e.printStackTrace()
        }

        return localVersion
    }

    private var exitTime: Long = 0

    override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (System.currentTimeMillis() - exitTime > 2000) {
                Toast.makeText(applicationContext, "再按一次退出程序",
                        Toast.LENGTH_SHORT).show()
                exitTime = System.currentTimeMillis()
            } else {
                finish()
                System.exit(0)
            }
        }
        return true
    }
}
